package com.mifengs.mall.ui.login;


import android.app.Activity;
import android.text.TextUtils;
import android.widget.Toast;

import com.hyphenate.chat.ChatClient;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.entity.TokenBean;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.event.WebFrgEvent;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.util.MD5Util;
import com.tencent.android.tpush.XGPushConfig;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lihaoqi on 2017/11/17.
 */

public class LoginPresent implements LoginContract.Presenter{


    private final LoginContract.View mView;

    public LoginPresent(LoginContract.View loginView) {
        this.mView = loginView;
    }

    @Override
    public void login() {
       /* String pwd = mView.getPwd().trim();
        String account = mView.getAccount();
        //mView.toUserCenter();
        HashMap<String,Object> hashMap = new HashMap<>();
//        hashMap.put("j_username",account);
//        hashMap.put("j_password",pwd);
//        hashMap.put("_spring_security_remember_me",true);
        hashMap.put("useraccount",account);
        hashMap.put("userpwd", MD5Util.toMD5(pwd));
        String pushToken = XGPushConfig.getToken(mView.getContext());
        if(!TextUtils.isEmpty(pushToken)){
            hashMap.put("usertoken",pushToken);
        }
        hashMap.put("mobiletype","1");
        mView.showLoading();
        NetWork.getLoginApi().loginGet(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseInfo<String>>bindToLife())
                .subscribe(new Observer<ResponseInfo<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        //checkLogin();
                    }

                    @Override
                    public void onNext(ResponseInfo<String> stringResponseInfo) {
                        mView.hideLoading();
                        switch (stringResponseInfo.getStatus()) {
                            case 200:
                                //checkLogin();
                                PreferenceUtils.saveToken(stringResponseInfo.getResult());
                                PreferenceUtils.saveUserMobile(MallApplication.getInstance(),mView.getAccount());
                                String hxName ="mfsc"+mView.getAccount().substring(3,mView.getAccount().length());
                                PreferenceUtils.saveHxUserName(MallApplication.getInstance(),hxName);
                                PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(),"mifengs");
                                if (!ChatClient.getInstance().isLoggedInBefore()) {
                                    hxCecLogin();
                                }
                                mView.showLongToast("登录成功");
                                EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                                ((Activity)mView).setResult(Activity.RESULT_OK);
                                mView.finish();
                                break;
                            case 201:
                                mView.showLongToast("登录失败");
                                break;
                            case 204:
                                mView.showLongToast("账户不存在");
                                break;
                            case 300:
                                mView.showLongToast("有空参数");
                                break;
                            case 301:
                                mView.showLongToast("密码错误");
                                break;
                            case 500:
                                mView.showLongToast("系统错误");
                                break;
                            default:
                                mView.showLongToast("登录失败");
                                break;
                        }

                    }
                });*/




        String pwd = mView.getPwd().trim();
        String account = mView.getAccount().trim();
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("mobile",account);
        hashMap.put("userpwd", MD5Util.toMD5(pwd));
        String pushToken = XGPushConfig.getToken(mView.getContext());
        if(!TextUtils.isEmpty(pushToken)){
            hashMap.put("usertoken",pushToken);
        }
        String code  = mView.getVerifyCode();
        if(!TextUtils.isEmpty(code)){
            hashMap.put("randNum",code);
        }
        hashMap.put("mobiletype","1");
        mView.showLoading();
        NetWork.getLoginApi().login(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBean<TokenBean>>bindToLife())
                .subscribe(new Observer<ResponseBean<TokenBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        mView.hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean<TokenBean> stringResponseInfo) {
                       mView.hideLoading();
                       String status = stringResponseInfo.getStatus();
                       if(status.equals(Constant.SUCCESS_CODE)){
                           PreferenceUtils.saveToken(stringResponseInfo.getParamer().getLoginToken());
                           PreferenceUtils.saveUserMobile(MallApplication.getInstance(),mView.getAccount());
                           String hxName ="mfsc"+mView.getAccount().substring(3,mView.getAccount().length());
                           PreferenceUtils.saveHxUserName(MallApplication.getInstance(),hxName);
                           PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(),"mifengs");
                           if (!ChatClient.getInstance().isLoggedInBefore()) {
                               hxCecLogin();
                           }
                           mView.showLongToast("登录成功");
                           EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                           ((Activity)mView).setResult(Activity.RESULT_OK);
                           mView.finish();
                       }else if(status.equals("1009")){
                           mView.showLongToast("密码输入错误次数超过3次,请输入验证码");
                           mView.hideOrShowCodeView(true);
                       }else{
                           mView.showLongToast(stringResponseInfo.getInfo());
                       }
                    }
                });

    }

    @Override
    public void hxCecLogin() {
        String userName = PreferenceUtils.getHxUserName(MallApplication.getInstance());
        String userPwd = PreferenceUtils.getHxUserPwd(MallApplication.getInstance());
        if(!"".equals(userName) && !"".equals(userPwd)){
            ChatClient.getInstance().login(userName, userPwd, new com.hyphenate.helpdesk.callback.Callback() {
                @Override
                public void onSuccess() {
//                mView.hxCecLoginSuccess();
                }

                @Override
                public void onError(int i, String s) {
//                    ToastUitl.show(s, Toast.LENGTH_SHORT);
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
        }
    }


    public void checkLogin(){
        boolean isLogin = PreferenceUtils.getLoginStatus();
        if(isLogin){
            PreferenceUtils.saveUserMobile(MallApplication.getInstance(),mView.getAccount());
            String hxName ="mfsc"+mView.getAccount().substring(3,mView.getAccount().length());
            PreferenceUtils.saveHxUserName(MallApplication.getInstance(),hxName);
            PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(),"mifengs");
            if (!ChatClient.getInstance().isLoggedInBefore()) {
                hxCecLogin();
            }
            mView.showLongToast("登录成功");
            EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
            EventBus.getDefault().post(new WebFrgEvent(WebFrgEvent.SYNCCOOKIES));
            mView.finish();
        }else{
            String error = PreferenceUtils.getError(mView.getContext());
            PreferenceUtils.saveError(mView.getContext(),"");
            if(error.equals("1")){
                mView.showLongToast("您输入的用户名或密码错误");
            }else{
                mView.showLongToast("登录失败");
            }
        }
    }


    @Override
    public void weixinLogin(final String weixinJson) {
        mView.showLoading();
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("jsonString",weixinJson);
        String pushToken = XGPushConfig.getToken(mView.getContext());
        if(!TextUtils.isEmpty(pushToken)){
            hashMap.put("usertoken",pushToken);
        }
        hashMap.put("mobiletype","1");
        NetWork.getLoginApi().weixinLogin(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBean<TokenBean>>bindToLife())
                .subscribe(new Observer<ResponseBean<TokenBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        mView.hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean<TokenBean> tokenBeanResponseInfo) {
                        mView.hideLoading();
                        String status = tokenBeanResponseInfo.getStatus();
                        if(status.equals(Constant.SUCCESS_CODE)){
                            PreferenceUtils.saveToken(tokenBeanResponseInfo.getParamer().getLoginToken());
                            String mobile = tokenBeanResponseInfo.getParamer().getLoginMobile();
                            PreferenceUtils.saveUserMobile(mView.getContext(),mobile);
                            String hxName ="mfsc"+mobile.substring(3,mobile.length());
                            PreferenceUtils.saveHxUserName(MallApplication.getInstance(),hxName);
                            PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(),"mifengs");
                            if (!ChatClient.getInstance().isLoggedInBefore()) {
                                hxCecLogin();
                            }
                            mView.showLongToast("登录成功");
                            EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                            ((Activity)mView).setResult(Activity.RESULT_OK);
                            mView.finish();

                        }else if (status.equals("1008")){
                            mView.toVerifyPhone(weixinJson);
                        }else{
                            ToastUitl.show(tokenBeanResponseInfo.getInfo(),Toast.LENGTH_SHORT);
                        }
                    }
                });
    }




}
